<?php
require("../model/userDao.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($_POST["action"] == "regist") {
        $uName = $_POST["uName"];
        $uPass = $_POST["uPass"];
        $agPass = $_POST["agPass"];
        // 验证两次密码是否一致
        if ($uPass != $agPass) {
            echo "<script>alert('两次密码不一致');history.back();</script>";
            exit;
        }

        if (trim($uName) == 'root') {
            echo "<script>alert('用户名已存在');history.back();</script>";
            exit;
        }

        // 检查用户名是否已存在
        $result = selectUserhome($uName, null);
        if (count($result) > 0) {
            echo "<script>alert('用户名已存在');history.back();</script>";
            exit;
        }
        // 处理文件上传
        $avatarName = 'default.jpg'; // 默认头像
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
            $uploadDir = '../image/avatar/';
            $avatarName = uniqid() . '_' . basename($_FILES['avatar']['name']);
            $targetFile = $uploadDir . $avatarName;
            // 移动上传的文件
            if (!move_uploaded_file($_FILES['avatar']['tmp_name'], $targetFile)) {
                $avatarName = 'default.png'; // 上传失败使用默认头像
            }
            echo "<script>console.log($avatarName)</script>";
        }
        // 插入用户数据
        $num = insertUser($uName, $uPass, $avatarName);
        if ($num > 0) {
            echo "<script>alert('注册成功');window.location.href='../view/index.php';</script>";
        } else {
            echo "<script>alert('注册失败');window.location.href='../view/index.php';</script>";
        }
    }
    // 登录功能
    else if ($_POST["action"] == "login") {
        $uName = $_POST["uName"];
        $uPass = $_POST["uPass"];
        session_start();
        pdLogin($uName, $uPass);
    }
}

/**
 * 判断是否是管理员函数
 * @param string $uName 用户名
 * @param string $uPass 用户密码
 * @return void
 */
function pdLogin($uName, $uPass)
{
    $result = selectUserhome($uName, $uPass);
    if (count($result) > 0) {

        $url = $result[0]['is_admin'] == 1 ? '../admin/index.php' : '../view/index.php';
        $msg = $result[0]['is_admin'] == 1 ? '管理登录成功' : '登录成功';
        $_SESSION['uid'] = $result[0]['uid'];
        $_SESSION['uName'] = $result[0]['is_admin'] == 1 ? '' : $uName;
        $_SESSION['hdb'] = $result[0]['is_admin'] == 1 ? $uName : '';
        echo "<script>document.cookie = 'user=$_SESSION[uName];path=/'</script>";
        echo "<script>alert('$msg');window.location.href='$url';</script>";
    } else {
        echo "<script>alert('用户名或密码错误');window.location.href='../view/index.php';</script>";
    }
}
//退出登录
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if ($_GET['action'] == 'out') {
        session_start();
        unset($_SESSION['uName']);
        unset($_SESSION['uid']);
        echo "<script>document.cookie = 'user=;path=/'</script>";
        echo "<script>window.location.href='../view/index.php';</script>";
    }
}
?>